import {
	queryUrl
} from "@/util/config";
import {
	login
} from "@/api/login";
const whiteList = ['/wx/wxLogin']
export default function http(path, params = {}, loading = true, method = "GET") {
	let retryCount = 1; //token失效，重试1次
	return new Promise((resolve, reject) => {
		if (loading) {
			uni.showLoading({
				title: "加载中",
				mask: true
			});
		}
		uni.request({
			header: {
				Authorization: whiteList.includes(path) ? "" : `Bearer ${uni.getStorageSync('token')}`,
				'x-source': 'wx',
				'Content-Type': "application/json"
			},
			url: queryUrl + path,
			method,
			data: params,
			async success(res) {
				uni.hideLoading();
				if (res.data?.code === 401) {
					if (retryCount > 0) {
						uni.login({
							success: async (loginRes) => {
								const token = await login({
									"code": loginRes.code,
								})
								uni.setStorageSync("token", token?.wx_token)
							}
						})
						retryCount--;
					}
				}
				console.log("请求url", path, " | 请求方法", method)
				console.log("参数", params)
				console.log("请求结果", res.data)
				resolve(res.data);
			},
			fail(err) {
				uni.hideLoading();
				uni.showToast({
					icon: "error",
					duration: 2000,
					title: "系统异常"
				});
				reject(err);
			},
			complete() {
				// uni.hideLoading();    // 在showToast之前执行会受影响
			}
		});
	});
};

/**
 * 替代 try-catch 的异步处理方式，参考了 https://github.com/scopsy/await-to-js
 * @template T
 * @param {Promise<T>} promise
 * @returns {Promise<[Error, undefined] | [null, T]>} 如果成功，则返回 [null, 异步处理结果]；如果失败，则返回 [Error, undefined]
 */
export const to = (promise) => promise
    .then((res) => {
        // 针对接口请求，只要状态码不为 200，就抛出异常
        if (res.code && res.code !== 200) {
            throw new Error(res.msg);
        }
        return [null, res];
    })
    .catch((err) => [err, undefined]);
